package com.base.monitor.module.biz.handler;

import com.base.monitor.model.enums.biz.CollectTypeEnum;
import com.base.monitor.model.model.biz.collect.entity.CollectData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 推送消防主机对应网关的在线时间
 */
@Component
@Slf4j
public class PushFireControlUpdateTimeHandler {

    private static final Map<Long, Date> fireControlOnlineTimeMap = new ConcurrentHashMap<>();

    @Autowired
    private HandleCollectDataHandler handleCollectDataHandler;

    @PostConstruct
    public void init() {
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
        scheduledExecutorService.scheduleWithFixedDelay(new CrtTask(), 30, 30, TimeUnit.SECONDS);
    }

    /**
     * 添加消防主机对应网关的在线时间
     * @param gatewayId 消防主机对应网关的ip
     */
    public static void addFireControlOnlineTimeMap(Long gatewayId) {
        fireControlOnlineTimeMap.put(gatewayId, new Date());
    }

    /**
     * 发送在线消息的任务类
     */
    private class CrtTask implements Runnable {

        @Override
        public void run() {
            synchronized (fireControlOnlineTimeMap) {
                for (Map.Entry<Long, Date> entry : fireControlOnlineTimeMap.entrySet()) {
                    List<String> list = new ArrayList<>();
                    list.add(entry.getKey() + "");
                    list.add(entry.getValue().getTime() + "");
                    handleCollectDataHandler.addTask(new CollectData("", CollectTypeEnum.FIRE, list));
                }
                fireControlOnlineTimeMap.clear();
            }
        }
    }
}
